package community.hospital.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import community.hospital.annotation.NeedLogin;
import community.hospital.common.CustomerException;
import community.hospital.common.LoginUserHolder;
import community.hospital.common.R;
import community.hospital.entity.response.UserResponse;

import community.hospital.util.JwtUtil;
import community.hospital.util.RedisUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static community.hospital.common.Constant.TOKEN_NAME;
import static community.hospital.common.RedisConstant.LOGIN_USER;
import static community.hospital.common.RedisConstant.SPLIT;
import static community.hospital.enums.BusinessEnum.TOKEN_ERROR;
import static community.hospital.enums.BusinessEnum.TOKEN_EXPIRE;

/**
 * @Author：ydj
 * @Date：2023/1/19 23:07
 */
@Component
public class NeedLoginInterceptor implements HandlerInterceptor {
    @Resource
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if ( !(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        NeedLogin annotation = handlerMethod.getMethodAnnotation(NeedLogin.class);
        if (annotation == null) {
            return true;
        }
        if (!annotation.value()) {
            return true;
        }
        //需要登录的用户
        String token = request.getHeader(TOKEN_NAME);
        Long userId = JwtUtil.getUserId(token);
        String loginUserKey = LOGIN_USER + SPLIT + userId;
        UserResponse userResponse = null ;
        if ((userResponse=redisUtil.get(loginUserKey,UserResponse.class))==null) {
            throw new CustomerException(TOKEN_EXPIRE);
        }
        //将用户注入上下文
        LoginUserHolder.setUser(userResponse);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
